
#import "VideoDescrib.h"
#import "CommentCell.h"
#import "AticleFootView.h"
#import "AticALLModel.h"
#import "Manager.h"
#import "PramasMontage.h"
#import "ChangyanSDK.h"
#import "ComCountModel.h"
#import "CommetModel.h"
#import "PassportModel.h"
#import "UserDataModel.h"
#import "ViewoFootView.h"
#import "NSString+ClearPPPP.h"
#import "NewsCell.h"
#import "VideoLIstModel.h"
#import "ImageBntCell.h"
#import "VideoDescCell.h"
#import "TOWebViewController.h"
#import "NSString+HtmlCharact.h"
#import "VideoView.h"
#import "TextPutView.h"
#import "ArticleHeadNaviView.h"
#import "LoginController.h"
#import "NewestAticleCtr.h"
#import "ShareView.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "CYCommentModel.h"
#import "NewsSectionHeadView.h"
#import "OtherInformationCtrl.h"
#import "MJRefresh.h"
#define recomCellHight 80
CG_INLINE void AlertLog (NSString *titleStr,NSString *message,NSString *button1,NSString *button2)
{
    if(!titleStr)
        titleStr = @"";
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: titleStr
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: button1
                                              otherButtonTitles: button2,
                              nil];
    [alertView show];
    
}

@interface VideoDescrib()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate,tableviewFresh,TextPutViewDeleget,CommentReplyDeleget,ArticleHeadNaviViewDeleget,PramClickDeleget,ShareViewDeleget>
{
    CGFloat _comentHight;//评论列表的高度
    AticALLModel *_allModel;//总Model
    
    DetailModel *_detaiModel;
    NEWAticListModel *_AticModel3;//推荐视频model
    NSInteger _PageNo;
    UserDataModel *_userModel;
}
@property (nonatomic,copy) NSString *TopicID;
@property (nonatomic,assign) NSInteger comentCount;
@property (nonatomic,strong) AticleFootView *footview;
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) NSMutableArray *commentAry;
@property (nonatomic,strong) NSArray *AtcImgList;
@property (nonatomic,strong) ViewoFootView *TBfootView;
@property (nonatomic,assign) CGFloat videCellHight;
@property (nonatomic,strong) NSArray *relateAry;
@property (nonatomic,strong) UILabel *decrLabel;
@property (nonatomic,strong) UIView *labelview;
@property (nonatomic,assign) CGFloat HightOfHead;
@property (nonatomic,assign) BOOL iSLabOpen;
@property (nonatomic,assign) CGFloat labOpenHight;
@property (nonatomic,strong) VideoLIstModel * videoListModel;
@property (nonatomic,assign) NSInteger comtId;
@property (nonatomic,assign) BOOL isComtClick;
@property (nonatomic,assign) CGFloat HightOfImgCell;
@property (nonatomic,assign) CGFloat Decribhight;
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,assign) int keyHight;
@property (nonatomic,assign) CGFloat textHight;
@property (nonatomic,strong)UIScrollView *scrollview;
@property (nonatomic,assign)BOOL clickWho;
@property (nonatomic,assign) CGFloat FootHeight;
@property (nonatomic,assign)BOOL cellHeight;
@property (nonatomic,strong) TextPutView *mytexetView;//发表评论View
@property (nonatomic,strong)VideoView *videoView;
@property (nonatomic,strong) ArticleHeadNaviView *articleHeadview;
@property (nonatomic,assign) NSInteger commentRow;
@property (nonatomic,strong)  ShareView *shareView;

@end

@implementation VideoDescrib
-(ShareView *)shareView{
    
    if (!_shareView) {
        CGFloat hhh = SCREEN_HEIGHT*0.49;
        
        if (kDIEIsIPhone4SOrLess) {
            hhh = SCREEN_HEIGHT*0.63;
        }
        
        if (kDIEIsIPhone5) {
            hhh = SCREEN_HEIGHT*0.53;
        }
        
        if (kDIEIsIPhone6P) {
            hhh = SCREEN_HEIGHT*0.47;
        }

        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - hhh, SCREEN_WIDTH, hhh)];
        _shareView.IsImageUrl = @"YES";
        _shareView.shareImageUrl =_detaiModel.share_img;
        _shareView.title = _detaiModel.title;
        _shareView.message =_detaiModel.share_message;
        _shareView.shareUrl = _detaiModel.share_url;
        _shareView.deleget = self;
    }
    return _shareView;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
    StatusBlack;
    self.articleHeadview.isLogin = self.app.isLogin;
   
}

-(TextPutView *)mytexetView{
    if (!_mytexetView) {
        _mytexetView = [[TextPutView alloc]initWithFrame:self.view.bounds];
        _mytexetView.alpha = 0;
        _mytexetView.deleget = self;
        _mytexetView.NoFace = YES;
        [self.view addSubview:_mytexetView];
    }
    return _mytexetView;
}

#pragma mark--获取评论data
-(void)GetCommentData{
    //获取评论数量  主要目的是获取文章的 topicID  从而获得评论内容
    __block NSDictionary *dic = [NSDictionary dictionary];
    [ChangyanSDK getCommentCount:nil topicSourceID:self.AticleID topicUrl:nil completeBlock:^(CYStatusCode statusCode, NSString *responseStr)
     {
         dic =  [Manager dictionaryWithJsonString:responseStr];
         ComCountModel *model = [[ComCountModel alloc]initWithDictionary:dic[@"result"][_AticleID] error:nil];
         _TopicID = model.id;
         [self getTopicCommentsWhithTopicID:model.id AndPageNo:1];
     }];
}


#pragma mark--获取评论列表
-(void)getTopicCommentsWhithTopicID:(NSString *)topicID AndPageNo:(NSInteger)pageNo{
    
    [ChangyanSDK getTopicComments:topicID
                         pageSize:@"5"
                           pageNo:[NSString stringWithFormat:@"%ld",(long)pageNo]
                          orderBy:nil
                            style:nil
                            depth:nil
                          subSize:nil
                    completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
//                        NSLog(@"++%@",responseStr);
                        NSDictionary *dic = [Manager dictionaryWithJsonString:responseStr];
                        
                        
                        CYCommentModel *cyModel = [[CYCommentModel alloc]initWithDictionary:dic error:nil];
                        //显示评论数量
                        _comentCount = cyModel.cmt_cnt.integerValue;
                        [self PublishView];
                        [_commentAry addObjectsFromArray:cyModel.comments];
                    
                        [_tableview reloadData];
                        [_tableview.footer endRefreshing];
                    }];
}
#pragma mark---下拉加载更多评论
-(void)loadMoreData{
    _PageNo ++;
    if (_commentAry.count<_comentCount) {
        
        [self getTopicCommentsWhithTopicID:_TopicID AndPageNo:_PageNo];
        
    }else{
        [_tableview.footer noticeNoMoreData];
    }
}

#pragma mark--发表评论
-(void)CommentWhithContent:(NSString *)content replyID:(NSString *)ReplyId{

    [ChangyanSDK submitComment:_TopicID
                       content:content
                       replyID:ReplyId
                         score:nil
                       appType:40
                       picUrls:nil
                      metadata:nil
                 completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                     
                     if ([responseStr rangeOfString:@"id"].length!=0) {
                         [_commentAry removeAllObjects];
                         [self GetCommentData];
                         
                         NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
                         [_tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                     }else{
                         [Manager GetHudWhithText:@"评论失败" AndFatherView:self.view];
                     }
                 }];
}

#pragma mark--视频详情数据
-(void)GetAFNt{
    
//    NSLog(@"%@",[PramasMontage AticleBidy:self.AticleID]);
    
    [[Manager sharedManager]RequestWhithURL:[PramasMontage AticleBidy:self.AticleID] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if (!error) {
        _allModel = [[AticALLModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
            _detaiModel =_allModel.article;
            _relateAry = _allModel.relate;
        
            self.videoListModel = [[VideoLIstModel alloc]initWithDictionary:responseObject[@"data"][@"video_list"] error:nil];
              _tableview.alpha = 1;
             self.videoView.allModel = _allModel;
            
            [UIView transitionWithView:self.view duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                
                [_tableview reloadData];
            } completion:nil];
        
            [self PublishView];
            [self GetCommentData];
            [MBProgressHUD hideHUDForView:self.view];
            
        }else{
            _tableview.tableHeaderView = nil;
            [MBProgressHUD hideHUDForView:self.view];
            [Manager GetHudWhithText:@"加载失败" AndFatherView:self.view];
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].statusBarStyle = 0;
    _PageNo =  1;
    self.view.backgroundColor = tabGropBackColor;
    _commentAry= [NSMutableArray array];
    [self NavView];
    [self creatHuD:nil];//创建加载菊花
    [self GetAFNt];
    
    self.TBfootView=[[ViewoFootView alloc]init];
    self.FootHeight = 200;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self CreactTableview];

}

-(void)CreatVideoWebView{
    self.videoView = [[VideoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 240)];
    
    self.videoView.deleget = self;
    self.videoView.isLogin = self.app.isLogin;
    _tableview.tableHeaderView = self.videoView;
}

-(void)PramClick{
    [self PramisAction];
}

-(void)NavView{
    
    self.articleHeadview = [[NSBundle mainBundle] loadNibNamed:@"ArticleHeadNaviView" owner:nil options:nil].lastObject;
    self.articleHeadview.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
    
    self.articleHeadview.UserName = self.UserName;
    self.articleHeadview.isVideo = @"YES";
    self.articleHeadview.AtcID = self.AticleID;
    self.articleHeadview.isLogin = self.app.isLogin;
    self.articleHeadview.deleget = self;
    self.articleHeadview.userModel = self.app.userModel;
    
    [self.view addSubview:self.articleHeadview];}

-(void)backCLick{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark---收藏操作代理方法
-(void)collectMaseege:(BOOL)IsHUD Message:(NSString *)message{
    if (_allModel) {
        if (IsHUD) {
            [Manager GetHudWhithText:message AndFatherView:self.view];
        }else{
            [self ToLOgin];
        }

    }else{
        [Manager GetHudWhithText:@"此功能暂时不能用" AndFatherView:self.view];
    
    }
}
#pragma mark---分享操作
-(void)ShareClick{
    if (_allModel) {
        
        if ([self.app.isLogin isEqualToString:@"YES"]) {
            [self.shareView show];
        }else{
        
             [self ToLOgin];
        }
       
    }else{
        [Manager GetHudWhithText:@"此功能暂时不能用" AndFatherView:self.view];
        
    }

}

#pragma mark---QQ空间单独事件
-(void)QzoneShare{
    NSString *utf8String = _detaiModel.share_url;
    NSString *title = _detaiModel.title;
    NSString *descriotion = _detaiModel.share_message;
    NSString *previewImageUrl = _detaiModel.share_url;
    
    NSArray* imageArray =@[previewImageUrl];
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKEnableUseClientShare];
        [shareParams SSDKSetupShareParamsByText:descriotion
                                         images:imageArray
                                            url:[NSURL URLWithString:utf8String]
                                          title:title
                                           type:SSDKContentTypeAudio];
        
        
        [ShareSDK share:SSDKPlatformSubTypeQZone
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             if (state == SSDKResponseStateSuccess)
             {
                 [self.shareView fadeOut];
             }
             else if (state == SSDKResponseStateFail)
             {
                 AlertLog(@"", @"分享失败", @"确定", nil);
             }
         }];
    }
}


#pragma mark--底部发表View
-(void)PublishView{
    
    [_footview removeFromSuperview];
    _footview = [[AticleFootView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-60, SCREEN_WIDTH, 60)];
    _footview.backgroundColor = [UIColor whiteColor];
    [_footview.textbtn addTarget:self action:@selector(footCommetView) forControlEvents:UIControlEventTouchUpInside];
    [_footview.comBtn setTitle:[NSString stringWithFormat:@"%ld",(long)_comentCount] forState:UIControlStateNormal];
    
    [_footview.comBtn addTarget:self action:@selector(CommentClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_footview];
    
}

-(void)CommentClick{
    
    NSIndexPath *indexPath;
    if (_comentCount!=0) {
        if (_commentAry.count>4) {
            indexPath =[NSIndexPath indexPathForRow:0 inSection:1];
        }else{
            indexPath=[NSIndexPath indexPathForRow:_commentAry.count-1 inSection:1];
        }
            [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
    }
}

#pragma mark--发送评论的TextView代理
-(void)DidSender:(NSString *)sendText{
    [self IssueComentAction:sendText];
    self.mytexetView.alpha = 0;
    self.isComtClick = YES;
}
#pragma mark--底部点击评论，进入发表评论的TextView;
-(void)footCommetView{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        self.mytexetView.alpha = 1;
         self.mytexetView.inputBar.placeHolder = @"说点什么呢?";
        [self.mytexetView.inputBar.textView becomeFirstResponder];
         
     }else{
     
         [self ToLOgin];
     }
}


-(void)CreactTableview{
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0,64, SCREEN_WIDTH, SCREEN_HEIGHT-64-58) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableview];
    _tableview.backgroundColor = tabGropBackColor;
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.tag = 1;
    _tableview.alpha = 0;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableview registerClass:[CommentCell class] forCellReuseIdentifier:@"commentCell"];
    [_tableview registerClass:[ImageBntCell class] forCellReuseIdentifier:@"imageCell"];
    
    _tableview.footer= [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _tableview.footer.automaticallyHidden = YES;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableview.width, 1)];
    view.backgroundColor = [UIColor clearColor];
    _tableview.tableFooterView = view;
    _tableview.sectionFooterHeight = 0.f;

        [self CreatVideoWebView];
        [self.view sendSubviewToBack:self.tableview];
}
#pragma mark - footView 视频简介的代理方法
-(void)tableviewFresh:(BOOL)clickWho
{
    CGSize size=[[[_detaiModel.body ClearPPP] filterresult] sizeWithFont:font(SCREEN_WIDTH*0.058) constrainedToSize:CGSizeMake(SCREEN_WIDTH-30, 100000)];
    
    self.FootHeight=size.height;
 
    if (!clickWho) {//如果是改变了Scrlloview的偏移 就对 self.cellHeight进行取反 让label回到偏移之前的状态
        
       self.cellHeight = !self.cellHeight;
    }
    
    if (self.cellHeight) {
        self.FootHeight=200;
    }
    
    self.cellHeight = !self.cellHeight;
    [_tableview reloadData];
}


#pragma mark - footView 相关视频的代理方法
-(void)RelateTableView
{
    if (kDIEIsIPhone6P) {
        self.FootHeight=self.relateAry.count*105+50;
    }else if (kDIEIsIPhone6){
    
        self.FootHeight=self.relateAry.count*97+50;
    }
    
    else{
        self.FootHeight=self.relateAry.count*85+50;
    }
    self.TBfootView.relateHeight=self.FootHeight;
    [_tableview reloadData];
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    if (_allModel) {
        if (section==0) {
            self.TBfootView.delegate=self;
            self.TBfootView.frame=CGRectMake(0, 0, SCREEN_WIDTH,self.FootHeight);
            self.TBfootView.VideoDescCellheight=self.FootHeight;
            self.TBfootView.model=_detaiModel;
            
            if (self.TBfootView.relateArr.count<_relateAry.count) {
                [self.TBfootView.relateArr addObjectsFromArray:_relateAry];
            }
            self.clickWho=YES;
            return self.TBfootView;
        }
        return nil;

    }else{
    
        return nil;
    }
}

#pragma mark - tableview代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
        if (section==1) {
            return  _commentAry.count;
        }else{
            return 1;
        }

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (_allModel) {
        if (section==0) {
            return self.FootHeight+40;
        }else{
            return 0;
        }
    }else{
        return 0;
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_allModel) {
        if (indexPath.section==0) {
            return self.HightOfImgCell+0.1;
        }else{
            return _comentHight+0.1;
        }
 
    }else{
        return 0;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    if (_allModel) {
        if (section==1) {
            return SCREEN_HEIGHT*0.08;
        }
        return 0;
    }else{
        return 0;
    }

    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (_allModel) {
        
        NewsSectionHeadView *view = [[NSBundle mainBundle]loadNibNamed:@"NewsSectionHeadView" owner:nil options:nil].lastObject;
        view.frame  = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.08);
        if (_commentAry.count!=0) {
            view.textShow.selected = NO;
        }else{
            view.textShow.selected = YES;
        }
            return view;
    }else{
        return nil;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (indexPath.section==0) {
        
        ImageBntCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageCell"];
        
        cell.allModel = _allModel;
        
        [cell refreshCell];
        [cell.primsBtn addTarget:self action:@selector(PramisAction) forControlEvents:UIControlEventTouchUpInside];
        
        __weak typeof(self) weakSelf = self;
        cell.MyBlock = ^(TOWebViewController *Towebctr){
            [weakSelf presentViewController:[[UINavigationController alloc] initWithRootViewController:Towebctr] animated:YES completion:nil];
        };
        self.HightOfImgCell = cell.cellHeight;
        return cell;
    }else{

        CommentCell *cell= [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
        cell.model = _commentAry[indexPath.row] ;
        cell.RowOfcell = indexPath.row;
        cell.deleget = self;
        _comentHight =cell.cellhight;
        
        return cell;
    }
}


#pragma mark---评论点赞操作
-(void)ComentPramClick:(NSString *)CommetID{
   
        if ([self.app.isLogin isEqualToString:@"YES"]) {
            
            if (self.app.ChangYanIsLogin) {
                
                [ChangyanSDK commentAction:1 topicID:_TopicID commentID:CommetID completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                    
                }];
            }
        }else{
            [self ToLOgin];
        }
}

#pragma mark---点击用户头像与用户名代理方法
-(void)HeadAndNameClickWhithId:(NSString *)uid{
    
    if (uid.length!=0&&uid!=0) {
        OtherInformationCtrl *other = [OtherInformationCtrl new];
        other.uid = uid;
        [self.navigationController pushViewController:other animated:YES];
    }
}

-(void)PramisAction{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        NSDictionary *dic = @{@"uid":self.app.userModel.uid,@"article_id":_AticleID};
        [[Manager sharedManager]ResponseWhithURL:@"http://school.diaoyur.cn/article/good-post" AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        }];
    }else{
        [self ToLOgin];
    }
}

#pragma mark---发表评论Action
-(void)IssueComentAction:(NSString *)Text{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        
        if (self.app.ChangYanIsLogin) {
            
            if (self.isComtClick == YES) {
                
                [self CommentWhithContent:Text replyID:[NSString stringWithFormat:@"%ld",(long)self.comtId]];
                
            }else{
                    [self CommentWhithContent:Text replyID:nil];
            }
        }else{
        [Manager GetHudWhithText:@"您的评论没有成功，请检查您的网络" AndFatherView:self.view];
        }
    }
}

-(void)ToLOgin{
    
    LoginController *login = [LoginController new];
    [self.navigationController pushViewController:login animated:YES];
}

#pragma mark--评论回复代理方法
-(void)CommentReply:(NSString *)ComentID UaerName:(NSString *)name Row:(NSInteger)row{
    
    [self footCommetView];
    self.mytexetView.inputBar.placeHolder =[NSString stringWithFormat:@"@%@",name];
    self.comtId = ComentID.integerValue;
    self.isComtClick = YES;
}

#pragma mark--相关视频点击代理方法
-(void)SelectRelateTablrView:(NSString *)AticID Skin:(NSNumber *)skin{
    if (skin.integerValue==1) {
        
        VideoDescrib *video = [VideoDescrib new];
        video.AticleID = AticID;
        [self.navigationController pushViewController:video animated:YES];
        
    }else{
    
        NewestAticleCtr *aticle = [NewestAticleCtr new];
        aticle.AticleID = AticID;
        [self.navigationController pushViewController:aticle animated:YES];
    }
}

@end